package org.ning.http;

import org.ning.model.Tag;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/7/5 14:29
 */
public class TimeUtils {

    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void parseTime(String dataStr, Tag tag){
        if(dataStr == null){
            tag.setBetween("未知");
            tag.setUpdateTime(LocalDate.of(1970,1, 1));
            return;
        }
        dataStr = dataStr.substring(0, dataStr.indexOf("."));
        String str = dataStr.replace("T", " ").replace("Z", "");
        LocalDateTime updateDateTime =   LocalDateTime.parse(str, TIME_FORMATTER );
        tag.setUpdateTime(LocalDate.from(updateDateTime));
        long betweenDays = ChronoUnit.DAYS.between(updateDateTime, LocalDateTime.now());
        String between = String.format("%d 天前", betweenDays);
        if(betweenDays == 0){

            long betweenHours = ChronoUnit.HOURS.between(updateDateTime, LocalDateTime.now());
            if(betweenHours == 0){
                between = "刚刚";
            }else {
                between = String.format("%d 小时前", betweenHours);
            }
        }else if(betweenDays>365){
            long betweenYears = ChronoUnit.YEARS.between(updateDateTime, LocalDateTime.now());
            between = String.format("%d 年前", betweenYears);
        }

        tag.setBetween(between);
    }

}
